import {Component, OnInit} from '@angular/core';
import {Observable} from 'rxjs/Observable';
import {BladeContainerBase} from '../../../../shared/blade/blade-container-base';
import {Blade} from '../../../../shared/blade/blade.model';
import {BladeData} from '../../../../shared/blade/blade-data';
import {TreeNode} from 'primeng/primeng';
import {List} from 'linqts';
import {DeviceEditComponent} from '../device-edit/device-edit.component';
import {Device} from '../../../../entity/device.model';
import {Model} from '../../../../entity/model.model';
import {Circuit} from '../../../../entity/circuit.model';
import {DeviceCategory} from '../../../../entity/device-category.model';
import {SubArray} from '../../../../entity/subarray.model';

import {Command} from '../../../../shared/toolbar.service';
import {DeviceService} from '../../../../service/device.service';
import {CircuitService} from '../../../../service/circuit.service';
import {ModelService} from '../../../../service/model.service';
import {DialogResult} from '../../../../shared/dialog.service';
import {DeviceCategoryService} from '../../../../service/device-category.service';
import {SubArrayService} from '../../../../service/sub-array.service';
import {TurboperCategory} from '../../../../entity/turboper-category.model';


@Component({
  selector: 'app-device-list',
  templateUrl: './device-list.component.html',
  styleUrls: ['./device-list.component.css']
})
export class DeviceListComponent extends BladeContainerBase<Device> {
  /**
   * 所有设备
   * @private
   * @type {Device[]}
   * @memberof DeviceListComponent
   */
  public devices: Device[] = [];
  /**
   * 过滤后的设备集合
   * @private
   * @type {Device[]}
   * @memberof DeviceListComponent
   */
  private devicesTemp: Device[] = [];
  /**
   * 所有线路
   * @private
   * @type {Device[]}
   * @memberof DeviceListComponent
   */
  private circuits: Circuit[] = [];
  /**
   * 所有节点
   *
   * @type {TreeNode[]}
   * @memberof DeviceListComponent
   */
  public files: TreeNode[] = [];
  /**
   * 过滤后的节点
   *
   * @type {TreeNode[]}
   * @memberof DeviceListComponent
   */
  public filesTemp: TreeNode[] = [];

  /**
   * 选中的节点
   *
   * @type {TreeNode[]}
   * @memberof DeviceListComponent
   */
  public selectedFile: TreeNode[] = [];
  /**
   * 所有型号
   * @private
   * @type {Device[]}
   * @memberof DeviceListComponent
   */
  private models: Model[] = [];
  /**
   * 所有设备类别
   * @private
   * @type {DeviceCategory[]}
   * @memberof DeviceListComponent
   */
  public deviceCategorys: DeviceCategory[] = [];
  /**
   * 所有光伏风场的设备类别
   * @private
   * @type {DeviceCategory[]}
   * @memberof DeviceListComponent
   */
  private photoDeviceCategorys: DeviceCategory[] = [];
  /**
   * 需要过滤的设备类别Id集合
   * @private
   * @type {DeviceCategory[]}
   * @memberof DeviceListComponent
   */
  private deviceCategoryIds: number[] = [];
  /**
   * 风场类型
   * @private
   * @type {DeviceCategory[]}
   * @memberof DeviceListComponent
   */
  private farmCategory: string;

  /**
   * 区域集合
   * @private
   * @type {Device}
   * @memberof DeviceListComponent
   */
  public subArrays: SubArray[] = [];

  /**
   * 所属父级Id集合
   * @private
   * @type {Device}
   * @memberof DeviceListComponent
   */
  private parentIds: number[] = [];

  isShow: boolean = false;

  constructor(
    private deviceService: DeviceService,
    private circuitService: CircuitService,
    private modelService: ModelService,
    private deviceCategoryService: DeviceCategoryService,
    private subArrayService: SubArrayService,) {
    super();
  }

  ngOnInit(): void {
    this.commands = [
      new Command('add', '添加', 'fa fa-plus', 'menu:insert', blade => this.exeAdd(blade), blade => this.canExeAdd(blade)),
      new Command('edit', '编辑', 'fa fa-edit', 'menu:update', blade => this.exeEdit(blade), blade => this.canExeEdit(blade)),
      new Command('delete', '删除', 'fa fa-trash-o', 'menu:delete', blade => this.exeDelete(blade), blade => this.canDelete(blade)),
    ];
    super.ngOnInit();
  }

  initData(): any | Observable<any> | Promise<any> {
    this.farmCategory = this.parentEntity.farmCategory;
    this.isShow = this.farmCategory == 'photovoltaic' ? true : false;
    const devicesGet = this.deviceService.getDevicesByFarmIdPhaseId(this.parentEntity.farmId, this.parentEntity.phaseId);
    const circuitGet = this.circuitService.getCircuitByFarmId(this.parentEntity.farmId);
    const modelGet = this.modelService.getModels();
    const DeviceCategorysGet = this.deviceCategoryService.getDeviceCategorys();
    const subArraysGet = this.subArrayService.getSubArrays();
    Promise.all([devicesGet, circuitGet, modelGet, DeviceCategorysGet, subArraysGet])
      .then(res => {
        this.bladeData.isLoading = false;
        if (res[0]) {
          this.devices = [...res[0]];
        }
        ;
        if (res[1]) {
          this.circuits = [...res[1]];
        }
        ;
        this.devices.forEach(device => {
          this.circuits.forEach(circuit => {
            if (device.circuitId === circuit.circuitId) {
              device.circuitName = circuit.circuitName;
            }
          });
        });
        if (res[2]) {
          this.models = [...res[2]];
        }
        ;
        this.devices.forEach(device => {
          this.models.forEach(model => {
            if (device.modelId === model.modelId) {
              device.modelName = model.modelName;
            }
          });
        });
        if (res[3]) {
          this.deviceCategorys = [...res[3]];
        }
        this.devices.forEach(device => {
          this.deviceCategorys.forEach(deviceCategory => {
            if (device.deviceCategoryId === deviceCategory.deviceCategoryId) {
              device.deviceCategoryName = deviceCategory.deviceCategoryName;
            }
          });
        });
        this.photoDeviceCategorys = [...this.deviceCategorys];
        this.photoDeviceCategorys.splice(this.photoDeviceCategorys.findIndex(o => o.deviceCategoryId == 1), 1)
        if (res[4]) {
          this.subArrays = [...res[4]];
        }
        this.devices.forEach(device => {
          this.subArrays.forEach(subArray => {
            if (device.subArrayId === subArray.subArrayId) {
              device.subArrayName = subArray.subArrayName;
            }
          });
        });
      })
      .catch(error => this.bladeData.error = error)
      .then(res => this.bladeData.isLoading = false)
  }

  /**
   * 递归初始化子菜单
   *
   * @param {Menu} menu
   * @param {TreeNode} treeNode
   * @memberof MenuListComponent
   */
  initChildMenu(device: Device, treeNode: TreeNode) {
    let childrenDevices = this.devices.filter(o => o.parentId == device.deviceId);
    if (childrenDevices != null && childrenDevices.length > 0) {
      let level: number = device.leave + 1;
      let list = new List(childrenDevices);
      let childrenTemp = list.OrderBy(o => o.seq).ToArray();
      device.children = childrenTemp;
      device.children.forEach(childrenDevice => {
        childrenDevice.leave = level;
        let childernTreeNode: TreeNode = {};
        childernTreeNode.data = childrenDevice;
        if (!treeNode.children) {
          treeNode.children = [];
        }
        treeNode.children.push(childernTreeNode);
        //递归
        this.initChildMenu(childrenDevice, childernTreeNode);
      });
    }
  }

  exeAdd(blend: Blade): void {
    let data: BladeData = new BladeData();
    data.id = 'deviceEdit';
    data.title = '设备创建';
    data.subtitle = '创建一个设备';
    data.isClosingDisabled = false;
    let createKeyBlade = this.bladeService.createBlade(DeviceEditComponent, data, true, null,
      {
        devices: this.devices,
        parent: this.currentEntity,
        isShow: this.isShow,
        subArrays: this.subArrays,
      });
    this.bladeService.showBlade(createKeyBlade, this.currentBlade);
  }

  canExeAdd(blend: Blade): boolean {
    return true;
  }

  exeEdit(blend: Blade): void {
    if (this.currentEntity != undefined) {
      let data: BladeData = new BladeData();
      data.id = 'deviceEdit';
      data.title = this.currentEntity.deviceName;
      let editBlade = this.bladeService.createBlade(DeviceEditComponent, data, false, this.currentEntity, {
        devices: this.devices,
        isShow: this.isShow,
        subArrays: this.subArrays,

      });
      this.currentBlade.bladeService.showBlade(editBlade, this.currentBlade);
    }
  }

  canExeEdit(blend?: Blade): boolean {
    // console.log(this.currentEntity)
    return this.currentEntity != null;
  }

  exeDelete(blend: Blade): void {
    let selectedDevices = this.getSelected();
    if (selectedDevices.length > 0) {
      this.dialogService
        .showConfirmationDialog('确认删除', '是否要删除选中项？')
        .subscribe(dialogResult => {
          if (dialogResult == DialogResult.Ok) {
            this.currentBlade.bladeData.isLoading = true;
            this.deviceService.batchDelete(selectedDevices.map(o => o.deviceId))
              .then(res => {
                if (res.code == '200') {
                  super.refresh(undefined);
                }
                if (res.code == '8001') {
                  this.dialogService
                    .showConfirmationDialog('删除失败', res.message);
                }
              })
              .catch(error => this.bladeData.error = error)
              .then(res => this.bladeData.isLoading = false);
          }
        })
    }
  }

  canDelete(blend?: Blade): boolean {
    return this.getSelected().length > 0;
  }

  getSelected(): Device[] {
    if (this.devices.length > 0) {
      let filter = this.devices.filter(ref => ref.isChecked)
      return filter == null ? [] : filter;
    }
    return [];
  }

  public onNodeSelect(event: any) {

    let node: TreeNode = event.node;
    node.expanded = !node.expanded;
    let device = event.node.data;
    this.currentEntity = device;
    // this.showCompanyEditBlade(device);
  }

  /**
   * 展开编辑弹出层
   *
   * @param {Setofkey} selectedKey
   *
   * @memberof DicKeyListComponent
   */
  // showCompanyEditBlade(device: Device) {
  //   if (this.currentEntity != device
  //     || this.bladeService.findBlade("deviceEdit") == undefined) {
  //     let data: BladeData = new BladeData();
  //     data.id = "deviceEdit";
  //     data.title = device.deviceName + "编辑";
  //     data.isClosingDisabled = false;
  //     let dicValueListBlade = this.bladeService.createBlade(DeviceEditComponent, data, false, device, { devices: this.devices });
  //     this.bladeService.showBlade(dicValueListBlade, this.currentBlade).then(res => {
  //       if (res) {
  //         this.currentEntity = device;
  //       }
  //     });
  //   }
  // }

  /**
   * 单选
   *
   * @param {any} event
   * @param {any} key
   *
   * @memberof
   */
  onItemCheack(event: HTMLInputElement, device: Device) {
    this.setChildrenChecked(device, event.checked);
    // this.setParenChecked(menu);
  }

  onSeletedChange(device: Device) {
    if (this.currentBlade.childrenCanDeactivate()) {
      this.currentEntity = device;
    }
  }

  onAllCheack(event: HTMLInputElement) {
    if (this.devices.length > 0) {
      for (let i = 0; i < this.devices.length; i++) {
        this.devices[i].isChecked = event.checked;
      }
    }
  }

  /**
   * 设置子菜单是否选中
   *
   * @param {Menu} menu
   * @param {boolean} isChecked
   * @memberof MenuListComponent
   */
  setChildrenChecked(device: Device, isChecked: boolean) {
    device.isChecked = isChecked;
    if (device.children && device.children.length) {
      device.children.forEach(childDevice => {
        this.setChildrenChecked(childDevice, isChecked);
      });
    }
  }

  deviceCategoryIsChecked(check: boolean, deviceCategory: DeviceCategory) {
    this.devices = [];
    if (check) {
      //过滤后的设备类别Id集合
      this.deviceCategoryIds.push(deviceCategory.deviceCategoryId);
      this.deviceCategoryIds.sort();
    } else {
      //过滤后的设备类别Id集合
      this.deviceCategoryIds.splice(this.deviceCategoryIds.findIndex(o => o == deviceCategory.deviceCategoryId), 1);
      this.deviceCategoryIds.sort();
    }

    if (this.deviceCategoryIds.length) {
      //过滤后的设备集合
      this.deviceCategoryIds.forEach(dc => {
        this.devices.push(...this.devicesTemp.filter(dt => dt.deviceCategoryId == dc))
      })
      this.files = [];
      let level: number = 1;
      this.devices.forEach(device => {
        device.leave = level;
        let treeNode: TreeNode = {};
        treeNode.data = device;
        this.files.push(treeNode);
      })
    } else {
      //过滤后的集合为空
      this.devices.push(...this.devicesTemp);
      this.files = [];
      let level: number = 1;
      let firstDevices = this.devices.filter(o => o.parentId == 0);
      if (firstDevices != null) {
        firstDevices = new List(firstDevices).OrderBy(o => Number(o.deviceName.slice(1))).ToArray();
        firstDevices.forEach(device => {
          device.leave = level;
          let treeNode: TreeNode = {};
          treeNode.data = device;
          this.files.push(treeNode);
          this.initChildMenu(device, treeNode);
        });
      }
    }
  }

}


// WEBPACK FOOTER //
// ./src/app/module/basic/device/device-list/device-list.component.ts
